package com.atguigu.day12;

import com.atguigu.bean.WaterSensor1;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;

public class Flink04_SQL_RegisterTable_WithStream {
    public static void main(String[] args) throws Exception {
        //1.获取流的执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        env.setParallelism(1);

        //2.获取表的环境
        StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env);

        //TODO 3.想将Table注册为带表名的表

        //从端口读取数据
        SingleOutputStreamOperator<WaterSensor1> streamSource = env.socketTextStream("localhost", 9999)
                .map(new MapFunction<String, WaterSensor1>() {
                    @Override
                    public WaterSensor1 map(String value) throws Exception {
                        String[] split = value.split(",");
                        return new WaterSensor1(split[0], Long.parseLong(split[1]), Integer.parseInt(split[2]));
                    }
                });

        //将流转为虚表（带表名）
        tableEnv.createTemporaryView("sensor",streamSource);

        tableEnv.executeSql("select id,sum(vc) as sumVc from sensor group by id").print();

        env.execute();
    }
}
